package cn.santi.controller;

import cn.santi.emuns.R;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/img")
public class ImgController {
    private final Path fileStorageLocation = Paths.get("E://hbx/").toAbsolutePath().normalize();
    //显示图片
    @GetMapping("/images/{filename:.+}")
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
        try {
            Path file = this.fileStorageLocation.resolve(filename).normalize();
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"").contentType(MediaType.IMAGE_JPEG).body(resource);
            } else {
                throw new RuntimeException("Could not read file: " + filename);
            }

        } catch (Exception e) {
            return ResponseEntity.ok().build();
        }
    }

    //保存到本地
    @PostMapping("/upload")
    public R handleFileUpload(@RequestParam("file") MultipartFile file) {
        System.out.println(file);
        if (file.isEmpty()) {
            return R.fail("文件不能为空");
        }
        try {
            // 指定文件保存的路径
            Path storagePath = Paths.get("E://hbx/");
            if (!Files.exists(storagePath)) {
                Files.createDirectories(storagePath);
            }

            // 生成新的文件名，使用UUID的前8位
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString().substring(0, 5) + fileExtension;
            Path targetPath = storagePath.resolve(newFilename);

            // 保存文件
            Files.copy(file.getInputStream(), targetPath);
            Map<Object, Object> map = new HashMap<>();
            map.put("newFilename", newFilename);
            map.put("targetPath", "img/images/" + newFilename);
            return R.ok(map);
        } catch (IOException e) {
            e.printStackTrace();
            return R.fail();
        }
    }
}
